<template>
  <div>
    <span>{{ showTime }}</span>
    <br>
    <button @click="stop">停止倒计时</button>
    <button @click="start">开始倒计时</button>
    <button @click="reset">重置倒计时</button>
  </div>
</template>

<script>
// 引入dayjs
import dayjs from 'dayjs'
export default {
  name: 'CountDown',
  data() {
    return {
      diff: 0, // 倒计时剩余时间
      endTime: 0 // 倒计时结束时间
    }
  },

  mounted() {
    // 设置倒计时结束时间
    this.endTime = dayjs().add(this.doneTime, "second")
    const now = dayjs()
    this.diff = this.endTime.diff(now)
    this.countDown()
  },

  props: {
    // 倒计时开始时间(单位/秒)
    doneTime: {
      type: Number,
      default: 58,
      validator(value) {
        // 自定义验证,必须是1-n的自然数
        if (/[1-9]\d*/.test(value)) {
          return true
        }
      }
    }
  },

  methods: {
    countDown() {
      // 定时触发倒计时事件,让倒计时开始
      this.timer = setInterval(res => {
        // 每隔一秒获取一下当前时间,并和endTime相减求差值
        const now = dayjs()
        const diff = this.endTime.diff(now)
        if (diff <= 0) {
          this.diff = 0
          // 停止定时器
          clearInterval(this.timer)
          // 定时器结束回调
          this.$emit("end")
          return
        }
        this.diff = diff
      }, 500)
    },

    start() {
      this.endTime = dayjs().add(this.diff, "millisecond")
      clearInterval(this.timer)
      this.countDown()
      // 计时器重新开始回调
      this.$emit("start")
    },

    stop() {
      clearInterval(this.timer)
      // 计时器停止回调,传参,此时还差多少秒
      this.$emit("stop",this.diff)
    },

    reset() {
      this.endTime = dayjs().add(this.doneTime, "second")
      clearInterval(this.timer)
      this.countDown()
      // 计时器重置回调
      this.$emit("reset")
    }
  },

  computed: {
    showTime() {
      // 计算剩余的天数、小时、分钟和秒数
      const days = Math.floor(this.diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((this.diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((this.diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((this.diff % (1000 * 60)) / 1000)

      return `倒计时: ${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`
    }
  }
}
</script>

<style scoped>
button {
  margin: 10px;
}
</style>
